#! /usr/bin/python
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 30 22:05:14 2016

@author: deanchen
"""

import urllib
import re
#import json
import sys, getopt
import simplejson as json

class LRM_Resources:
    
    #def __init__(self):
    
    global res_list 
    res_list = [] 
    
    def main(self,argv):
        
        try:            
            opts, args = getopt.getopt(sys.argv[1:], "hn:s:S:a:i:",["help"])
        except getopt.GetoptError:
            print 'please use resource_search.py -h for detail'
            sys.exit(2)
        
        for option, value in opts:
            try: 
                if option in ["-h","--help"]:
                    print """
        usage: ./resource_search.py [-n|-a|-s|-S|-i] args                
                
            -n    check resouce information with name;
            -s    check card information with card's SN
            -S    check chassis information with chassis' SN
            -a    check resource information with IP address
            -i    check interface connection for all/specific interface
                    
        Examples:
        
            ./resource_search.py -n slt104-banana
            ./resource_search.py -a 10.208.85.3
            ./resource_search.py -s CAAB1441
            ./resource_search.py -S DB1116AK1098
            ./resource_search.py -n slt104-banana -i all
            ./resource_search.py -n slt104-banana -i ge-0/0/0.0
                    
                """
                    sys.exit(1)
            
                elif option == '-n':
                
                    print ("#"*30)
                    self.chk_res_with_name(value)
                    #self.chk_res_interface(value)
                
                    s = sys.argv
                
                    if len(s) == 5 and s[3] == '-i':
                        print ("~"*30)
                        if s[4] == 'all':
                            self.chk_res_interface(value)
                        else:
                            self.chk_specific_interface(value,s[4])
                    else:
                        pass
                #sys.exit(1)
                    print ("#"*30)
                elif option == '-s':
                
                    print ("#"*30)
                    self.chk_card_with_SN(value)
                #sys.exit(1) 
                    print ("#"*30)
                elif option == '-S':
                
                    print ("#"*30)
                    self.chk_chassis_with_SN(value)
                #sys.exit(1)
                    print ("#"*30)
                elif option == '-a':
                
                    print ("#"*30)
                    self.chk_res_with_IP(value)
                    print ("#"*30)
            except IndexError:
					print "Opps ~ can not find it on LRM."
					print "Maybe it is in the LAB storage."
					print "Please double check with LAB."
					print ("#"*30)
    def chk_res_with_domain(self,domain_name):
        
        domain_res = urllib.urlopen("http://inception.juniper.net/lrm/core/resource/search.json?domain_name=%s&is_active=true" %domain_name).read()
        json_res = json.loads(domain_res)
        num_rows = json_res[u"num_rows"]
        
        for i in range(num_rows):
            res_list.append(json_res[u"rows"][i][u"name"])

            
        
    def chk_res_with_name(self,name):
        
        #get name,model,mgt ip,rack,elevation
        lrm_url = urllib.urlopen("http://inception.juniper.net/lrm/core/resource/search.json?name=%s&is_active=true&_chassis_and_interface" %name).read()
        json_lrm = json.loads(lrm_url)
        
        
        #create dict
        #keys = ('name','model','mgt','rack','elevation','reserved_by')
        keys = ('name','model','mgt','rack','reserved_by')
        dict = {}.fromkeys(keys)
        
        #add value to dict
        dict['name'] = json_lrm[u"rows"][0][u"name"]
        dict['rack'] = json_lrm[u"rows"][0][u"rack"]+"_"+str(json_lrm[u"rows"][0][u"elevation"]).split('.')[0]
        #dict['rack'] = json_lrm[u"rows"][0][u"rack"]
        #dict['elevation'] = int(json_lrm[u"rows"][0][u"elevation"])
        dict['model'] = json_lrm[u"rows"][0][u"model"]
        dict['mgt'] = json_lrm[u"rows"][0][u"mgt_ip_address"]
        
        dict_reservation = json_lrm[u"rows"][0][u"reservation"]
        
        if 'by_user' in dict_reservation.keys():
            dict['reserved_by'] = json_lrm[u"rows"][0][u"reservation"][u"by_user"]
        else:
            dict['reserved_by'] = 'Null'
        

        for key in dict.keys():
            print key + ' : ' + str(dict[key])
        
    def chk_card_with_SN(self,sn):
        
        lrm_url = urllib.urlopen("http://inception.juniper.net/lrm/core/component/search.json?serial_number=%s&_flat&" %sn).read()
        json_lrm = json.loads(lrm_url)
        #print json_lrm
        #create dict
        keys = ('chassis','model','label','chassis_rack')
        dict = {}.fromkeys(keys)
        
        #add value to dict
        dict['chassis'] = json_lrm[u"rows"][0][u"chassis_resource_name"][0]
        dict['model'] = json_lrm[u"rows"][0][u"model"]
        dict['label'] = json_lrm[u"rows"][0][u"label"]
        dict['chassis_rack'] = json_lrm[u"rows"][0][u"chassis_rack"]

        #print dict
        for key in dict.keys():
            print key + ' : ' + str(dict[key])

    def chk_chassis_with_SN(self,sn):
        
        lrm_url = urllib.urlopen("https://inception.juniper.net/lrm/core/chassis/search.json?serial_number=%s&_hierarchical" %sn).read()
        json_lrm = json.loads(lrm_url)
        
        keys = ('chassis','model','rack','elevation')
        dict = {}.fromkeys(keys)
        
        dict['chassis'] = json_lrm[u"rows"][0][u"chassis_resource"][0][u"resource"][u"name"]
        dict['model'] = json_lrm[u"rows"][0][u"chassis_model"][u"name"]
        dict['rack'] = json_lrm[u"rows"][0][u"chassis_rack"][u"name"]
        dict['elevation'] = json_lrm[u"rows"][0][u"elevation"]
        
        #print dict
        for key in dict.keys():
            print key + ' : ' + str(dict[key])
    
    
    def chk_res_with_IP(self,ip):

        lrm_url = urllib.urlopen("https://inception.juniper.net/lrm/core/resource/search.json?management_ip=%s" %ip).read()
        json_lrm = json.loads(lrm_url)
        
        chassis_name = json_lrm[u"rows"][0][u"name"]
        self.chk_res_with_name(chassis_name)
        
        
    def chk_res_interface(self,name):
        
        lrm_url = urllib.urlopen("https://inception.juniper.net/lrm/core/logical_interface/search.json?resource_name=%s&_flat&" %name).read()
        json_lrm = json.loads(lrm_url)

        local_int = []
        remote_int = []
        dict_int = {}
        
        for logical_int in json_lrm[u"rows"]:
            
            #put local int in list local_int
            local_int.append(logical_int['name'])
            #put remote int in list remote_int
            remote_int.append(logical_int['switch'])
            

        #generate dict for interfaces   
        dict_int = dict(map(lambda x,y:[x,y],local_int,remote_int))
        print dict_int
        
    def chk_specific_interface(self,name,interface):
        
        lrm_url = urllib.urlopen("https://inception.juniper.net/lrm/core/logical_interface/search.json?resource_name=%s&_flat&" %name).read()
        json_lrm = json.loads(lrm_url)

        local_int = []
        remote_int = []
        dict_int = {}
        
        for logical_int in json_lrm[u"rows"]:
            
            #put local int in list local_int
            local_int.append(logical_int['name'])
            #put remote int in list remote_int
            remote_int.append(logical_int['switch'])
            

        #generate dict for interfaces   
        dict_int = dict(map(lambda x,y:[x,y],local_int,remote_int))
        print interface +' : '+dict_int[interface]
    def write_to_mysql(self):
        
        self.chk_res_with_domain('pdt-regression')
        list_two = res_list[0:3]
        print list_two
        
        for device in list_two:
            
            self.chk_res_with_name(device)


a = LRM_Resources()
#a.write_to_mysql()
a.main(sys.argv[1:])
#a.chk_res_interface('slt101-tiger')
#a.chk_card_with_SN('CAAB1441')
#a.chk_res_with_IP('10.208.181.1')


    
